package prj.common.web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import prj.common.service.CaptchaService;

public class CaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
		processRequest(request, response);
	} 


	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	                 throws ServletException, IOException {
		processRequest(request, response);
	}
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		String sessionKey = CaptchaService.CAPTCHA_SESSION_KEY + request.getParameter("field");
		String captchaText = (String)request.getSession().getAttribute(sessionKey);
		BufferedImage captchaImage = CaptchaService.generateCaptchaImage(captchaText, Integer.parseInt(request.getParameter("w")), Integer.parseInt(request.getParameter("h")));
		response.setContentType("image/png");
		OutputStream os = response.getOutputStream();
		ImageIO.write(captchaImage, "png", os);
		os.close();
	}
}
